<template>
  <a-layout id="components-layout-demo-top-side">
    <a-layout-content style="padding: 0 50px">
      <a-form layout="inline" :form="form">
        <a-layout style="padding: 24px 0; background: #fff">
          <a-layout-sider width="300" style="background: #fff">
            <div style="height:800px;overflow:auto">
              <h2 style="text-align:center">试题总数： {{questions.length}}</h2>
              <h2 style="text-align:center">试卷总分： {{ this.elsum }}</h2>
              <a-button type="primary" style="left: 85px" icon="check" @click="handleSubmit">
                保存试卷
              </a-button>
              <a-card style="top: 30px" v-for="item in subjectList" :key="index">
                <a-card :title="item.quTypeKey" :style="{ marginTop: '16px' }">
                  <a slot="extra" href="#">删除</a>
                  共 {{item.count}} 题，共 {{item.count * parseInt(item.sum) }} 分<br />
<!--                  共 {{this.quantity}} 题，共 {{parseInt(this.fraction) * parseInt(this.quantity)}} 分<br />-->
                  每题
                  <a-form-item>
                     <a-input style="width: 60px"  onkeyup="value=value.replace(/[^\d]/g,'')"  v-model="item.sum" size="small"  @change="InputText"/>
                  </a-form-item>
                  分
                </a-card>
              </a-card>

            </div>
          </a-layout-sider>
          <a-layout-content :style="{ padding: '0 24px', minHeight: '280px' }">
            <a-card >
              <a-form-item label="考试名称"  style="left: 60px;" >
                <a-input style="width: 400px" v-decorator="['title', { rules: [{ required: true, message: 'Please input your note!' }] }]" />
              </a-form-item>
              <a-form-item label="考试难度" style="left: 60px;">
                <a-select style="width: 400px" v-decorator="['level',{ rules: [{ required: true, message: 'Please select your gender!' }] },]" >
                  <a-select-option v-for="(b, index) in quLevelList" :key="index" :value="b.key">
                    {{b.value}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-card>

              <a-modal
                title="操作"
                :width="800"
                v-model="visible"
                @ok="handleChange"
              >
                选择题库:<a-select :size="size" default-value="a1" style="width: 300px;" label-in-value @change="ElRepoById">
                  <a-select-option v-for="(v, index) in ElRepoList" :key="index" :value="v.id" >
                    {{v.title}}
                  </a-select-option>
                </a-select>
<!--                题型:<a-input v-model="quTypeKey" disabled="false" style="width: 300px"/>-->
                <a-table
                  size="default"
                  ref="table"
                  rowKey="id"
                  :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
                  :columns="columns"
                  :dataSource="QuList"
                >
                  <span slot="qutype" slot-scope="text">{{text | quTypeFilter}}</span>
                </a-table>

              </a-modal>

            <a-form-item label="添加新的大题" style=" top: 8px" >
              <a-select :size="size" default-value="a1" style="width: 200px;" label-in-value  @change="visibleChange">
                <a-select-option v-for="(b, index) in quTypeList" :key="index" :value="b.dictValue">
                  {{b.dictLabel}}
                </a-select-option>
              </a-select>
            </a-form-item>


            <a-list size="large" bordered :data-source="questions" :style="{ margin: '16px 0' }">
              <a-list-item slot="renderItem" slot-scope="item, index">
                <h3>{{ (index+1) +').'}} {{ item.content }}</h3><br>
                <template  v-for="(i,b) in item.el">
                  <a-avatar :style="{ backgroundColor: i.isRight===1?'#00BFFF':'#DCDCDC'}">{{String.fromCharCode(65 + b)}}</a-avatar>
                  {{ i.content }}<br><br>
                </template>
              </a-list-item>
              <div slot="header">
                  <a-input style="width: 200px" v-model="quTypeKey"  disabled/>
                  <a-button style="left: 10px;" icon="plus" @click="visibleChange">添加题目</a-button>
              </div>
            </a-list>
          </a-layout-content>
        </a-layout>
      </a-form>
    </a-layout-content>
  </a-layout>

</template>

<script>
import {getElRepoList} from '@/api/elRepo'
import { getElQuList, infoQuEl } from '@/api/elQu'
import { STable } from '@/components'
import { checkPermission } from '@/utils/permissions'
import { getDictArray } from '@/utils/dict'
import {savePaper} from '@/api/elPaper'


const quTypeMap = {}
export default {
  name: 'TableList',
  components: {
    STable
  },
  data() {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      visibleChangeform: this.$form.createForm(this),
      mdl: {},
      quType: '',
      quTypeKey: '',
      subjectList: [],
      ElRepoList: [],
      QuList: [],
      total: 0,
      elsum: 0,
      form: this.$form.createForm(this),
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 表头
      columns: [
        {
          title: '题型',
          dataIndex: 'quType',
          scopedSlots: { customRender: 'qutype' }
        },
        {
          title: '题目内容',
          dataIndex: 'content'
        },
        {
          title: '创建时间',
          dataIndex: 'createTime',
        }
      ],
      questions: [],
      visible: false,
      selectedRowKeys: [],
      selectedRows: [],
      addEnable: checkPermission('system:elQu:add'),
      editEnabel: checkPermission('system:elQu:edit'),
      removeEnable: checkPermission('system:elQu:remove'),
      quTypeList: [],
      getElQuList: [],
      quLevelList: [
        {
          key: 1,
          value: '简单'
        },
        {
          key: 2,
          value: '较难'
        }
      ],
      quantity: '1'
    }
  },
  filters: {
    quTypeFilter(type) {
      return quTypeMap[type]
    }
  },
  created() {
    getDictArray('qu_type').then(res => {
      this.quTypeList = res
      res.map(item => {
        quTypeMap[item.dictValue] = item.dictLabel
      })
    })
  },
  methods: {
    InputText(){
      this.elsum = 0
      this.subjectList.forEach(item=>{
        this.elsum = this.elsum + (item.count * item.sum)
      })
    },
    ElRepoById(val){
      this.QuList = []
      val.rid = val.key
      val.quType = this.quType
      getElQuList(val).then(item => {
        for (let i = 0; i < item.rows.length; i++) {
          infoQuEl(item.rows[i].id).then(res => {
            //简单题目答案
            item.rows[i].repoId = val.key
            item.rows[i].el = res.el
          })
          if (item.rows[i].id === this.selectedRowKeys[i]){

          }else{
            this.QuList.push(item.rows[i])
          }
        }
      })
    },
    handleChange(val){
      this.total = 0
      let _questions = this.selectedRows
      _questions.forEach(item=>{
        this.total++
        this.questions.push(item)
      })

      // console.log(this.selectedRowKeys)
      // var total = 0
      // for (let i = 0; i < this.selectedRowKeys.length; i++) {
      //     total++
      // }
      this.subjectList.push(
        {
          'quTypeKey': this.quTypeKey,
          'quType': this.quType,
          'count': this.total,
          'sum': 0
        }
      )
      console.log(this.subjectList)
      this.visible = false;
    },
    visibleChange(value){
      this.QuList = []
      getElRepoList().then(item => {
        this.ElRepoList = item.rows
      })
      this.quTypeKey= value.label
      this.quType = value.key
      // this.subjectList.push(this.quTypeKey)
      this.visible = true;
    },
    onSelectChange(selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    handleAdd() {
      this.$refs.modal.add()
    },
    handleEdit(record) {
      // console.log(record)
      // this.$refs.modal.edit(record)
    },
    handleOk() {
      this.$refs.table.refresh(true)
      console.log('handleSaveOk')
    },
    handleSubmit(parameter) {
      this.form.validateFields((err,values)=>{
        values.rows = this.questions
        values.repo =this.subjectList
        console.log(values)
        if (!err){
          savePaper(values).then(res=>{
            if (res.code===0){
              this.$message.success('保存成功')
              this.$emit('ok')
              this.$router.push({ path: '/elPaperList' })
            }else {
              this.$message.error(res.msg)
            }
          })
        }

      })
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
<style>
.background {
  height: 700px;
  color: #FFFFFF;
  overflow: auto;
  box-shadow: #F0F0F0 0px 0px 10px;
}

.m2 {
  background: #13c2c2;
}
</style>
